<div>
  <div class="mb-5">
    <div class="flex justify-between">
      <a-typography-title :level="3">电视剧分类</a-typography-title>
      <div>
        <a-button type="primary" class="flex" @click="modelOpenHandle">
          <template #icon>
            <svg class="icon" aria-hidden="true" style="color: white">
              <use xlink:href="#icon-jiahao"></use>
            </svg>
          </template>
          <span class="ml-2">新增</span>
        </a-button>
      </div>
    </div>
    <easy-data-table :headers="cols" :items="classifyList" hide-footer show-index>

      <template #item-name="item">
        <a-input v-if="editableData[item.id]" v-model:value="editableData[item.id].name" class="text-xs"
          style="margin: -5px 0"></a-input>
        <template v-else>
          <span> {{item.name}}</span>
        </template>
      </template>


      <template #item-idx="item">
        <a-input v-if="editableData[item.id]" v-model:value="editableData[item.id].idx" class="text-xs"
          style="margin: -5px 0"></a-input>
        <template v-else>
          <span> {{item.idx}}</span>
        </template>
      </template>

      <template #item-show="item">
        <a-switch @change="showChangeHandle(item)" :checked="item.show=='1'?true: false" checked-children="显示"
          un-checked-children="隐藏" />
      </template>
      <template #item-action="item">
        <span v-if="editableData[item.id]">
          <span class="span_link cursor-pointer mr-2" @click="tableSaveHandle(item)">保存</span>
          <a-popconfirm title="确认取消编辑吗？" ok-text="确定" cancel-text="取消" @confirm="tableCancelHandle(item)">
            <span class="span_link cursor-pointer mr-2">取消</span>
          </a-popconfirm>
        </span>
        <span v-else class="span_link cursor-pointer mr-2" @click="tableEditHandle(item)">编辑</span>

        <a-popconfirm title="确定要删除这个分类吗？" ok-text="确定" cancel-text="取消" @confirm="confirmDelete(item)">
          <span class="span_link cursor-pointer ">删除</span>
        </a-popconfirm>
      </template>

      <template #empty-message>
        <div class="flex items-center flex-col">
          <div>
            暂时还没有数据哟，<span class="span_link cursor-pointer" @click="modelOpenHandle">立即添加</span>
          </div>
          <div style="width:120px; height: 120px;">
            <img src="/public/images/no_data.svg" />
          </div>
        </div>
      </template>

    </easy-data-table>
  </div>
  <a-modal :width="720" v-model:open="modelOpen" cancel-text="取消添加" ok-text="确认添加" title="新增电视剧分类" @ok="modelOkHandle">
    <div class="w-full flex flex-row">
      <div class="w-6/12">
        <a-form-item label="分类名称" class="w-11/12" :validate-status="v$.name.$error?'error':'success'"
          :help="errors.name">
          <a-input placeholder="请输入分类名称" v-model:value="classifyData.name" @blur="v$.name.$touch" />
        </a-form-item>
      </div>
      <div class="w-6/12">
        <a-form-item label="分类排序" class="w-11/12" :validate-status="v$.idx.$error?'error':'success'" :help="errors.idx">
          <a-input placeholder="请输入分类排序" v-model:value="classifyData.idx" @blur="v$.idx.$touch" />
        </a-form-item>
      </div>
    </div>
    <div class="w-full flex flex-row">
      <div class="w-6/12">
        <a-form-item label="是否显示" class="w-11/12">
          <a-switch v-model:checked="classifyData.show" checked-children="显示" un-checked-children="隐藏" />
        </a-form-item>
      </div>
    </div>
    <div>
      <a-typography-paragraph type="secondary">
        注意<br />
        排序的值越大，显示的时候越靠后。
      </a-typography-paragraph>
    </div>
  </a-modal>
</div>
<script>
  let columnsData = [
    {
      text: '分类名称',
      value: 'name',
    },
    {
      text: '排序',
      value: 'idx',
    },
    {
      text: '是否展示',
      value: 'show',
    },
    {
      text: '操作',
      value: 'action',
    },
  ];
  function useValidate(classifyData) {
    const { required, maxLength, helpers } = VuelidateValidators;
    const rules = computed(() => {
      return {
        name: {
          required: helpers.withMessage('分类名称是必填项~', required)
        },
        idx: {
          required: helpers.withMessage('请输入分类排序位置~', required)
        },
      };
    });
    const v$ = Vuelidate.useVuelidate(rules, classifyData);
    const errors = ref({});
    for (let item in rules.value) {
      errors.value[item] = computed(() => {
        let errors = [];
        v$.value[item].$errors.forEach(e => {
          errors.push(e.$message);
        });
        return errors;
      });
    }
    return {
      v$,
      errors
    };
  }

  function useModel(classifyData, Validate) {

    const modelOpen = ref(false);

    const modelOpenHandle = () => {
      modelOpen.value = true;
    }
    const modelOkHandle = async () => {
      let validResult = await Validate.v$.value.$validate();
      if (!validResult) {
        Hint.warn('请正确填写表单信息');
        return;
      }
      let ret = await axios.post("/v1/web/tv/classify/add", classifyData);
      if (ret.data.code != 200) {
        Hint.error(ret.data.msg);
        return;
      }
      reload({ hint_msg: ret.data.msg });
    }
    return {
      modelOpen,
      modelOkHandle,
      modelOpenHandle,
    }
  }
  function useMain() {
    const classifyList = ref([]);
    const editableData = reactive({});
    const classifyData = reactive({
      name: "",
      idx: 99,
      show: true
    })
    const Validate = useValidate(classifyData);


    const tableSaveHandle = async params => {
      let id = params.id;
      let body = _.pick(editableData[id], ['name', 'id', 'idx']);
      let ret = await axios.post('/v1/web/tv/classify/update', body);
      delete editableData[id];
      if (ret.data.code != 200) {
        Hint.error("保存修改失败，请稍后重试~");
        return;
      }
      reload({ hint_msg: ret.data.msg, });
    }
    const tableCancelHandle = params => {
      delete editableData[params.id];
    }
    const tableEditHandle = params => {
      let id = params.id;
      editableData[id] = _.cloneDeep(classifyList.value.filter(item => id === item.id)[0]);
    }
    const confirmDelete = async params => {
      let id = params.id;
      try {
        let ret = await axios.post('/v1/web/tv/classify/delete', { id });
        await getClassify();
        if (ret.data.code != 200) {
          Hint.error(ret.data.msg);
        }
        reload({ hint_msg: ret.data.msg });
      } catch (e) {
        console.log(e);
        Hint.error("删除分类失败");
      }
    }
    const showChangeHandle = async params => {
      let body = {};
      for (let itm of classifyList.value) {
        if (itm.id == params.id) {
          itm.show = itm.show == '1' ? '0' : '1';
          body = _.pick(itm, ['show', 'id'])
          break;
        }
      }
      let ret = await axios.post('/v1/web/tv/classify/update', body);
      if (ret.data.code != 200) {
        Hint.error("隐藏显示失败，请稍后重试~");
        return;
      }
      Hint.success("隐藏显示成功~");
    }
    const getClassify = async () => {
      try {
        let ret = await await axios.post('/v1/web/tv/classify' );
        classifyList.value = ret.data.data;
      } catch (e) {
        let msg = `获取电视剧分类失败`;
        Hint.error(msg);
        console.log(msg, e);
      }
    };
    onMounted(async () => {
      await getClassify();
    })
    return {
      cols: ref(columnsData),
      classifyList,
      editableData,
      classifyData,
      showChangeHandle,
      tableSaveHandle,
      tableCancelHandle,
      tableEditHandle,
      confirmDelete,
      ...Validate,
      ...useModel(classifyData, Validate)
    }
  }
</script>